// 封装axios请求
// 导入axios是全局的axios
import axios from 'axios'
import { getToken } from '@/utils/storage'
import JSONBig from 'json-bigint'

const request = axios.create({
  // 基准地址
  baseURL: 'http://ttapi.research.itcast.cn',
  // 超时,如果接口超过3000毫秒,直接失败
  timeout: 3000,
  transformResponse: [function (data) {
    let result
    try {
      result = JSONBig.parse(data)
    } catch {
      result = data
    }
    return result
  }],
  // 自动把默认的Content-Type改成 表单格式Content-Type:application/x-www-form-urlencoded
  transformRequest: [function (data) {
    return JSON.stringify(data)
  }],
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  const token = getToken()
  if (token) {
    config.headers.Authorization = 'Bearer ' + getToken()
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

export default request
